<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container" v-show="showSearch">
      <div class="search-row">
        <!-- 订单编号搜索 -->
        <div class="search-item">
          <label class="search-label">订单编号:</label>
          <el-input
            v-model="queryParams.number"
            placeholder="手机号、订单号"
            clearable
            class="search-input"
            @keyup.enter="handleQuery"
          />
        </div>
        
        <!-- 订单状态搜索 -->
        <div class="search-item">
          <label class="search-label">订单状态:</label>
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            class="search-select"
            @change="handleQuery"
          >
            <el-option label="待支付" value="0" />
            <el-option label="已支付" value="1" />
            <el-option label="已完成" value="2" />
            <el-option label="已取消" value="3" />
          </el-select>
        </div>
        
        <!-- 预约时间搜索 -->
        <div class="search-item">
          <label class="search-label">预约时间:</label>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            class="search-datepicker"
            @change="handleDateRangeChange"
            clearable
          />
        </div>
        
        <!-- 搜索按钮 -->
        <div class="search-buttons">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </div>
      </div>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['orderManagement:maintenance:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['orderManagement:maintenance:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['orderManagement:maintenance:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['orderManagement:maintenance:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="borderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="number" width="150" />
      <el-table-column label="服务名称" align="center" prop="serviceDetailsName" width="120">
        <template #default="scope">
          <span>{{ scope.row.serviceDetailsName || '汽车保养' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商家" align="center" prop="carMerchantName" width="120" />
      <el-table-column label="客户" align="center" width="120">
        <template #default="scope">
          <div>{{ scope.row.carUserName }}</div>
          <div class="text-xs text-gray-500">{{ scope.row.carUserPhone }}</div>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" width="120">
        <template #default="scope">
          <div>原价: ¥{{ scope.row.serviceDetailsPresentPrice || 0 }}</div>
          <div>优惠: ¥{{ scope.row.carCouponPreferentialMoney || 0 }}</div>
          <div class="font-bold text-red-500">实付: ¥{{ scope.row.price }}</div>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">待支付</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="primary">已支付</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="success">已完成</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="danger">已取消</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="reservationTime" width="130">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reservationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['orderManagement:maintenance:query']">详情</el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['orderManagement:maintenance:edit', 'orderManagement:maintenance:remove']">
            <el-button link type="primary" class="ml-2">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit" v-hasPermi="['orderManagement:maintenance:edit']">修改</el-dropdown-item>
                <el-dropdown-item command="delete" v-hasPermi="['orderManagement:maintenance:remove']">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改保养订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="borderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input-number v-model="form.userId" placeholder="请输入用户id" :min="1" controls-position="right" class="!w-full" />
        </el-form-item>
        <el-form-item label="订单编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="核销码【UUID产生、唯一】" prop="verificationCode">
          <el-input v-model="form.verificationCode" placeholder="请输入核销码【UUID产生、唯一】" />
        </el-form-item>
        <el-form-item label="核销码图片" prop="verificationImg">
          <el-input v-model="form.verificationImg" placeholder="请输入核销码图片" />
        </el-form-item>
        <el-form-item label="下单时间" prop="orderTime">
          <el-date-picker clearable
            v-model="form.orderTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择下单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="reservationTime">
          <el-date-picker clearable
            v-model="form.reservationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单车辆id号" prop="carId">
          <el-input-number v-model="form.carId" placeholder="请输入订单车辆id号" :min="1" controls-position="right" class="!w-full" />
        </el-form-item>
        <el-form-item label="优惠券id【每次只使用一张】" prop="couponId">
          <el-input-number v-model="form.couponId" placeholder="请输入优惠券id" :min="1" controls-position="right" class="!w-full" />
        </el-form-item>
        <el-form-item label="实付价格" prop="price">
          <el-input-number v-model="form.price" placeholder="请输入实付价格" :min="0" :precision="2" controls-position="right" class="!w-full" />
        </el-form-item>
        <el-form-item label="支付状态" prop="payStatus">
          <el-select v-model="form.payStatus" placeholder="请选择支付状态" class="!w-full">
            <el-option label="未支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="支付失败" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker clearable
            v-model="form.payTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择订单状态" class="!w-full">
            <el-option label="待支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已取消" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="删除状态" prop="deleted">
          <el-select v-model="form.deleted" placeholder="请选择删除状态" class="!w-full">
            <el-option label="正常" :value="0" />
            <el-option label="已删除" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否评价" prop="evaluate">
          <el-select v-model="form.evaluate" placeholder="请选择是否评价" class="!w-full">
            <el-option label="未评价" value="0" />
            <el-option label="已评价" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Maintenance">
import { listMaintenance, getMaintenance, delMaintenance, addMaintenance, updateMaintenance } from "@/api/vehicle/orderManagement/maintenance"

const { proxy } = getCurrentInstance()

const borderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const dateRange = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: null,
    phone: null,
    number: null,
    startTime: null,
    endTime: null
  },
  rules: {
    userId: [
      { required: true, message: "用户id不能为空", trigger: "blur" }
    ],
    number: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
    carId: [
      { required: true, message: "订单车辆id号不能为空", trigger: "blur" }
    ],
    price: [
      { required: true, message: "实付价格不能为空", trigger: "blur" },
      { type: "number", message: "实付价格必须为数字值", trigger: "blur", transform: (value) => Number(value) }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 处理日期范围变化 */
function handleDateRangeChange(dates) {
  if (dates && dates.length === 2) {
    queryParams.value.startTime = dates[0]
    queryParams.value.endTime = dates[1]
  } else {
    queryParams.value.startTime = null
    queryParams.value.endTime = null
  }
}

/** 查询保养订单列表 */
function getList() {
  loading.value = true
  listMaintenance(queryParams.value).then(response => {
    borderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    number: null,
    verificationCode: null,
    verificationImg: null,
    orderTime: null,
    reservationTime: null,
    carId: null,
    couponId: null,
    price: null,
    payStatus: 0,
    payTime: null,
    status: 0,
    deleted: 0,
    evaluate: null
  }
  proxy.resetForm("borderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  queryParams.value.status = null
  queryParams.value.phone = null
  queryParams.value.number = null
  queryParams.value.startTime = null
  queryParams.value.endTime = null
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加保养订单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMaintenance(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改保养订单"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["borderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMaintenance(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMaintenance(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除保养订单编号为"' + _ids + '"的数据项？').then(function() {
    return delMaintenance(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('orderManagement/maintenance/export', {
    ...queryParams.value
  }, `maintenance_${new Date().getTime()}.xlsx`)
}

/** 查看详情按钮操作 */
function handleView(row) {
  // 跳转到订单详情页面，传递完整的订单数据
  proxy.$router.push({
    path: '/vehicle/orderManagement/orderManagementDetails',
    query: {
      orderId: row.id,
      orderData: JSON.stringify(row) // 传递完整的订单数据
    }
  })
}

/** 处理下拉菜单命令 */
function handleCommand(command, row) {
  switch (command) {
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
  }
}

getList()
</script>

<style scoped>
.search-container {
  background: #f5f7fa;
  padding: 16px 20px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
  font-weight: 500;
}

.search-input {
  width: 200px;
}

.search-select {
  width: 120px;
}

.search-datepicker {
  width: 280px;
}

.search-buttons {
  margin-left: auto;
  display: flex;
  gap: 12px;
}

.search-buttons .el-button {
  padding: 8px 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-row {
    flex-wrap: wrap;
  }
  
  .search-buttons {
    margin-left: 0;
    margin-top: 8px;
  }
}

@media (max-width: 768px) {
  .search-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .search-input,
  .search-select,
  .search-datepicker {
    width: 100%;
    min-width: 200px;
  }
}
</style>